﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLDC.Common.Estate;
using ZLDC.Topo.Model.Estate;
using System.Data;


namespace ZLDC.Estate.CM
{
    public partial class CustomerDetail : _PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hUserID.Value = this.info.m_sUserID;
                this.ddept.Value = this.info.m_sDeptName;
                this.ddeptid.Value = this.info.m_sDeptID;
                this.duser.Value = this.info.m_sUserName;
                this.duserid.Value = this.info.m_sUserID;

                btnCompetences();

                setUrl();

                ZLDC.Topo.BLL.Estate.SystemParamBLL.LoadParamType(followType, false, "跟进方式(客)");
                ZLDC.Topo.BLL.Estate.SystemParamBLL.LoadParamType(customerClass, false, "等级");                
            }
        }

        // 权限控制按钮
        private void btnCompetences()
        {
            int id = _Request.GetInt("id", 0);
            int userid = _Convert.ToInt(this.info.m_sUserID, 0);            
            string station = this.info.m_sStation;   // 职称
            string deptid_list = CacheUtility.Cache_GetAllChildDept(this.info.m_sDeptID);

            // 1分行经理及以上级别
            string SalesManagerStation = _Utility.GetWebConfigSetting("SalesManagerStation");

            if (id > 0)
            {               
                ZLDC.Topo.Model.Estate.CustomerInfo info = CacheCustomer.Cache_Detail_Info(id);

                if (info != null)
                {
                    if (info.IsChange > 0)
                    {
                        Lbadduser.InnerText = "转介人:";
                        Lbadduserdept.InnerText = "转介人部门:";
                    }
                    
                    // 判断是否是该客的管理者                    
                    if (SalesManagerStation.Contains(station) && deptid_list.Contains(info.OwnerDeptId.ToString()))
                        hIsManager.Value = "1";
                    // 判断是否是最原始客源的管理者                    
                    if (SalesManagerStation.Contains(station) && deptid_list.Contains(info.AddDeptId.ToString()))
                        hIsManager1.Value = "1";
                    //转介客原始人
                    DataTable dt=ZLDC.Topo.BLL.Estate.ChangecustomerLogBLL.p_CustomerChangelog_ChangeUserId(id);
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            hChangeUserId.Value = this.info.m_sUserID;
                            hChangeStatus.Value = dt.Rows[0]["status"].ToString();
                        }
                    }

                    ///成交客按钮权限  判断是否是：“私客”，“交易类型”,“是否有效”
                    if (info.IsValid == 0)
                    {
                        if (info.Status.ToString() == "2")
                        {
                            this.btnToDeal.Text = "取消成交";
                        }
                        else
                        {
                            this.btnToDeal.Text = "转成交";
                        }
                        if ((info.OwnerDeptId.ToString() == this.info.m_sDeptID && ZLDC.Common.BaseUser.UserInfo.GetPopedom("转成交客")) || ZLDC.Common.BaseUser.UserInfo.GetPopedom("转全部成交客"))
                        {
                            btnToDeal.Visible = true;
                        }
                        else if (SalesManagerStation.Contains(this.info.m_sStation))//区域经理
                        {
                            string GetParentIdById = ZLDC.DAL.Estate.DeptDAL.GetParentIdById(info.OwnerDeptId);

                            if (GetParentIdById == this.info.m_sDeptID && ZLDC.Common.BaseUser.UserInfo.GetPopedom("转成交客"))
                            {
                                this.btnToDeal.Visible = true;
                            }
                        }
                    }


                    if (info.Mark1 == "1")
                    {
                        btnInfo1.Visible = false;
                        btnInfo2.Visible = false;
                        btnChange.Visible = false;
                    }

                    if (info.Status == 0)
                    {
                        btnToDatum.Text = "转资料";
                    }
                    else if (info.Status == 1)
                    {
                        btnToDatum.Text = "转当前";
                    }
                    if (info.Ownerid.ToString() == _Utility.GetInfoBySession().m_sUserID && info.IsChange != 1)
                    {
                        btnToDatum.Visible = true;
                    }


                    if (_Utility.GetWebConfigSetting("SalesManagerStation").Contains(station))
                    {
                        hManagerChangIsSelf.Value = "1";//经理级以上转私客指定人员;
                    }

                    if (this.info.m_sRoleID=="1")//管理员
                    {
                        hManagerChangIsSelf.Value = "1";
                    }

                    if (info.IsSelf == 0)//是私客
                    {
                        // IsChange 0 非转介 1转介客待审  2已成功的转介客
                        if (info.IsChange == 0)//不是转介客
                        {
                            if ((_Utility.GetWebConfigSetting("SalesManagerStation").Contains(station) && deptid_list.Contains(info.OwnerDeptId.ToString()))
                                || info.Ownerid == userid)//自己的私客,经理以上和自己可以操作以下按钮
                            {
                                btnInfo1.Visible = false;//转私客
                                btnInfo2.Visible = true;//转公客
                                if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("转介客"))
                                    btnChange.Visible = true;
                                else
                                    btnChange.Visible = false;
                                btnToDatum.Visible = true;
                                if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除客源"))
                                    btnDelete.Visible = true;
                                else
                                    btnDelete.Visible = false;
                            }
                            else //非所属自己的私客,任何按钮都不可操作
                            {
                                btnInfo1.Visible = false;//转私客
                                btnInfo2.Visible = false;//转公客
                                btnChange.Visible = false;
                                btnToDatum.Visible = false;
                                btnToDeal.Visible = false;
                                btnDelete.Visible = false;
                            }
                        }
                        else if (info.IsChange > 0)//是转介客
                        {
                            if ((_Utility.GetWebConfigSetting("SalesManagerStation").Contains(station) && deptid_list.Contains(info.AddDeptId.ToString()))
                                || info.AddUId == userid)//转介方的私客,经理以上和自己可以操作以下按钮
                            {
                                btnInfo1.Visible = false;//转私客
                                btnInfo2.Visible = true;//转公客
                                if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("转介客"))
                                    btnChange.Visible = true;
                                else
                                    btnChange.Visible = false;
                                btnToDatum.Visible = true;
                                btnToDeal.Visible = true;
                                if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除客源"))
                                    btnDelete.Visible = true;
                                else
                                    btnDelete.Visible = false;
                            }
                            else //接收方的私客,任何按钮都不可操作
                            {
                                btnInfo1.Visible = false;//转私客
                                btnInfo2.Visible = false;//转公客
                                btnChange.Visible = false;
                                btnToDatum.Visible = false;
                                btnToDeal.Visible = false;
                                btnDelete.Visible = false;
                            }
                            //接收人接收后才有转介权限
                            if (info.IsChange == 2 )
                            {
                                if ((_Utility.GetWebConfigSetting("SalesManagerStation").Contains(station) && deptid_list.Contains(info.OwnerDeptId.ToString()))
                                    || info.Ownerid == userid)//自己的私客,经理以上和自己可以操作以下按钮
                                {
                                    if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("转介客"))
                                        btnChange.Visible = true;
                                    else
                                        btnChange.Visible = false;
                                }

                            }

                        }
                    }
                    else
                    {
                        if (!ZLDC.Common.BaseUser.UserInfo.GetPopedom("转私客"))
                            btnInfo1.Visible = false;
                        else
                            btnInfo1.Visible = true;//转私客
                        btnInfo2.Visible = false;//转公客
                        btnChange.Visible = false;
                        btnToDatum.Visible = false;
                        btnToDeal.Visible = false;
                        if (!ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除客源"))
                            btnDelete.Visible = false;
                        else
                            btnDelete.Visible = true;
                    }

                    //成交客时：隐藏转当前转资料按钮
                    if (info.Status.ToString() == "2")
                    {
                        this.btnToDatum.Visible = false;
                    }


                    // 在客源转出方离职后，接收人可以将客源转为公客或者删除 0 非转介 1转介客待审  2已成功的转介客
                    if (info.IsChange == 2)
                    {
                        string outmsg = "";
                        if (ZLDC.Topo.BLL.Estate.ChangecustomerLogBLL.p_customer_ischange_public(userid, id, out outmsg) > 0)
                        {
                            btnDelete.Visible = true;
                            btnInfo2.Visible = true;
                        }
                    }
                    


                    if(info.IsChange>0)
                        btnChange.Visible = false;//如果是转介客，隐藏转介按钮
                }

                // 转公客的权限判断
                if (!ZLDC.Common.BaseUser.UserInfo.GetPopedom("转公客"))
                    btnInfo2.Visible = false;
                else
                    btnInfo2.Visible = true;

            }
            
        }

        // 设置 首条 上一条 下一条 尾条 
        private void setUrl()
        {
            string id = _Request.GetString("id");               // 当前ID
            string id_list = _Request.GetString("id_list");     // 所有ID字符串
            if (id_list.IndexOf(",") < 0)
            {
                btnFirst.Visible = false;
                btnPrev.Visible = false;
                btnNext.Visible = false;
                btnLast.Visible = false;

                return;
            }

            string[] m_sIdiList = id_list.Split(',');   // 所有ID数组
            int m_nPos = 0;

            //检查位置
            int listLength = m_sIdiList.Length;
            for (int i = 0; i < listLength; i++)
            {
                if (m_sIdiList[i] == id)
                {
                    m_nPos = i;
                    break;
                }
            }

            this.btnFirst.Attributes["onclick"] = "javascript:window.location.href='CustomerDetail.aspx?id=" + m_sIdiList[0] + "&id_list=" + id_list + "';return false;";
            if (m_nPos != 0)
            {
                this.btnPrev.Enabled = true;
                this.btnFirst.Enabled = true;
                this.btnPrev.Attributes["onclick"] = "javascript:window.location.href='CustomerDetail.aspx?id=" + m_sIdiList[m_nPos - 1] + "&id_list=" + id_list + "';return false;";
            }
            else
            {
                this.btnPrev.Enabled = false;
                this.btnFirst.Enabled = false;
            }
            if (m_nPos != m_sIdiList.Length - 1)
            {
                this.btnNext.Enabled = true;
                this.btnLast.Enabled = true;
                this.btnNext.Attributes["onclick"] = "javascript:window.location.href='CustomerDetail.aspx?id=" + m_sIdiList[m_nPos + 1] + "&id_list=" + id_list + "';return false;";
            }
            else
            {
                this.btnNext.Enabled = false;
                this.btnLast.Enabled = false;
            }
            this.btnLast.Attributes["onclick"] = "javascript:window.location.href='CustomerDetail.aspx?id=" + m_sIdiList[m_sIdiList.Length - 1] + "&id_list=" + id_list + "';return false;";
        }

        /// <summary>
        /// 客源状态转换   0：当前,1 资料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnToDatum_Click(object sender, EventArgs e)
        {
            int id = _Request.GetInt("id");               // 当前ID

            string outmsg = "";
            if (btnToDatum.Text == "转当前")
            {
                outmsg = ZLDC.Topo.BLL.Estate.CustomerBLL.CustomerToDatum(id, 0);
                if (outmsg == "操作成功")
                {
                    ZLDC.Topo.BLL.Estate.CustomerBLL.p_Customerfollow_save(0, id, _Convert.ToInt(_Utility.GetInfoBySession().m_sDeptID), _Utility.GetInfoBySession().m_sDeptName, _Convert.ToInt(_Utility.GetInfoBySession().m_sUserID), _Utility.GetInfoBySession().m_sUserName, "", "资料->当前", 0, 0);
                    btnToDatum.Text = "转资料";
                }
            }
            else if (btnToDatum.Text == "转资料")
            {
                outmsg = ZLDC.Topo.BLL.Estate.CustomerBLL.CustomerToDatum(id, 1);
                if (outmsg == "操作成功")
                {

                    btnToDatum.Text = "转当前";
                    ZLDC.Topo.BLL.Estate.CustomerBLL.p_Customerfollow_save(0, id, _Convert.ToInt(_Utility.GetInfoBySession().m_sDeptID), _Utility.GetInfoBySession().m_sDeptName, _Convert.ToInt(_Utility.GetInfoBySession().m_sUserID), _Utility.GetInfoBySession().m_sUserName, "", "当前->资料", 0, 0);

                }
            }

            _Cache.RemoveLike(CacheConst.CACHE_CUSTOMER_FOLLOW_JSON + id);
            _Cache.Remove(CacheConst.CACHE_CUSTOMER_DETAIL_JSON + id.ToString());
            _Cache.Remove(CacheConst.CACHE_CUSTOMER_DETAIL_INFO + id.ToString());

            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('" + outmsg + "');</script>");
        }

        /// <summary>
        /// 经理级公客转私客指定接客人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btToPty_Click(object sender, EventArgs e)
        {
            int id = _Convert.ToInt(hID.Value, 0);

            if (id <= 0)
            {
                _JavaScript.Alert(this.Page, "请先选择您要操作的客源");
                return;
            }
            DataSet ds = ZLDC.Topo.BLL.Estate.CustomerBLL.SelectIsSelfById(id);

            string mark1 = ds.Tables[0].Rows[0]["mark1"].ToString();
            if (mark1 == "1")
            {
                _JavaScript.Alert(this.Page, "对不起，待审客源不能转为私客！");
                return;
            }
            string userNoAndName = tbMakeUser.Text;      // 工号及名称

            if (userNoAndName.Trim().Equals(""))
            {
                _JavaScript.Alert(this.Page, "接客人不能为空");
                return;
            }

            string userName = string.Empty; // 姓名
            string userNo = string.Empty;   // 工号
            int userId = 0;                 // 楼盘系统用户ID
            _Utility.GetUserNoAndUserName(userNoAndName.Trim(), out userName, out userNo);
            userId = ZLDC.Topo.BLL.Estate.UserBLL.GetUserIDByUserName(userName,userNo);

            // 更新开盘人及开盘人部门信息
            UserInfo info = ZLDC.Topo.BLL.Estate.UserBLL.GetUserInfoByUserID(userId);

            int deptid = info.Dept_id;
            string deptname = info.DeptName;
            int userid = info.Id;
            string username = info.Name;

            string outmsg = "";
            ZLDC.Topo.Model.Estate.CustomerInfo custInfo = ZLDC.Topo.BLL.Estate.CustomerBLL.p_customer_detail(id);
            string tradetype = custInfo.Tradetype;    // 交易类型

            if(custInfo.IsSelf == 0)
            {
                outmsg = "已被\"" + custInfo.Owner + "[" + custInfo.OwnerDept + "]\"转为私客，无法重复转客";
                _JavaScript.Alert(this.Page, outmsg);
                return;               
            }

            outmsg = ZLDC.Topo.BLL.Estate.CustomerBLL.ManagerChangeIsSelf(id, userid, username, deptid, deptname);
            if (outmsg.Contains("操作成功"))
            {
                ZLDC.Topo.BLL.Estate.CustomerBLL.p_Customerfollow_save(0, id, _Convert.ToInt(_Utility.GetInfoBySession().m_sDeptID), _Utility.GetInfoBySession().m_sDeptName, _Convert.ToInt(_Utility.GetInfoBySession().m_sUserID), _Utility.GetInfoBySession().m_sUserName, "", "公客转私客，接客人：" + deptname + "," + username + "", 0, 0);

                // 添加量化                
                ZLDC.Topo.BLL.Estate.quantificationBLL.UpdateCustomerChangeQuantification(id, tradetype, deptid, deptname, userid, username);
            }

            // 更新缓存
            if (id > 0)
            {
                _Cache.RemoveLike(CacheConst.CACHE_CUSTOMER_FOLLOW_JSON + id);
                _Cache.Remove(CacheConst.CACHE_CUSTOMER_DETAIL_JSON + id.ToString());
                _Cache.Remove(CacheConst.CACHE_CUSTOMER_DETAIL_INFO + id.ToString());
            }

            btnCompetences();
            _JavaScript.Alert(this.Page, outmsg);
        }

        /// <summary>
        /// 转成交客
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnToDeal_Click(object sender, EventArgs e)
        {
            int id = _Convert.ToInt(hID.Value, 0);

            if (id <= 0)
            {
                _JavaScript.Alert(this.Page, "请先选择您要操作的客源");
                return;
            }
            int status = 0;
            string content = "";
            if (btnToDeal.Text == "转成交")
            {
                status = 2;
                content = "转成交客";
            }
            else
            {
                status = 1;
                content = "取消成交客";
            }
            string outmsg = ZLDC.Topo.BLL.Estate.CustomerBLL.CustomerToDatum(id, status);
            if (outmsg == "操作成功")
            {
                ZLDC.Topo.BLL.Estate.CustomerBLL.p_Customerfollow_save(0, id, _Convert.ToInt(_Utility.GetInfoBySession().m_sDeptID), _Utility.GetInfoBySession().m_sDeptName, _Convert.ToInt(_Utility.GetInfoBySession().m_sUserID), _Utility.GetInfoBySession().m_sUserName, "", content, 0, 0);
            }

            _Cache.RemoveLike(CacheConst.CACHE_CUSTOMER_FOLLOW_JSON + id);
            _Cache.Remove(CacheConst.CACHE_CUSTOMER_DETAIL_JSON + id.ToString());
            _Cache.Remove(CacheConst.CACHE_CUSTOMER_DETAIL_INFO + id.ToString());

            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('" + outmsg + "');</script>");
        }

    }
}
